<template>
    <el-button type="primary" @click="addUser()" v-hasDelPermission="'user:add'">新增用户</el-button>
    <el-button type="danger" @click="batchDel()" v-hasDelPermission="'user:delete'">批量删除</el-button>
    <el-table
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
        <!-- 复选框    -->
        <el-table-column type="selection" width="33%" />
        <el-table-column type="index" label="序号" width="52%" />
        <el-table-column prop="loginAct" label="账号" width="90%" show-overflow-tooltip />
        <el-table-column property="name" label="姓名" width="75%" show-overflow-tooltip />
        <el-table-column property="phone" label="联系电话" show-overflow-tooltip />
        <el-table-column property="email" label="邮箱" show-overflow-tooltip />
        <el-table-column property="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column label="操作" show-overflow-tooltip>
            <template #default="scope">
                <el-button type="primary" @click="view(scope.row.id)" v-hasDelPermission="'user:view'">详情</el-button>
                <el-button type="success" @click="edit(scope.row.id)" v-hasDelPermission="'user:edit'">编辑</el-button>
                <el-button type="danger" @click="del(scope.row.id)" v-hasDelPermission="'user:delete'">删除</el-button> 
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <div class="parent">
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :total="total"
            @prev-click="toPage"
            @next-click="toPage"
            @current-change="toPage"
        />
    </div>
     <!-- 新增用户的弹窗(对话框) -->
     <el-dialog v-model="dialogVisible" label-width="10%" :title="Title" width="55%" draggable>
        <el-form ref="userRefForm" :model="newUser" :rules="userRules">
            <el-form-item label="账号:" prop="loginAct">
                <el-input v-model="newUser.loginAct"/>
            </el-form-item>
            <el-form-item label="密码:" v-if="newUser.id">
                <el-input
                    v-model="newUser.loginPwd"
                    type="password"
                    placeholder="密码默认不可见,可在此修改"
                    show-password
                />
            </el-form-item>
            <el-form-item label="密码:" prop="loginPwd" v-else>
                <el-input
                    v-model="newUser.loginPwd"
                    type="password"
                    show-password
                />
            </el-form-item>
            <el-form-item label="姓名:" prop="name">
                <el-input v-model="newUser.name"/>
            </el-form-item>
            <el-form-item label="联系电话:" prop="phone">
                <el-input v-model="newUser.phone"/>
            </el-form-item>
            <el-form-item label="邮箱:" prop="email">
                <el-input v-model="newUser.email" type="email"/>
            </el-form-item>
            <el-form-item label="账号未过期:" prop="accountNoExpired">
                <el-select v-model="newUser.accountNoExpired" placeholder="请选择">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="密码未过期:" prop="credentialsNoExpired">
                <el-select v-model="newUser.credentialsNoExpired" placeholder="请选择">              
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="账号未锁定:" prop="accountNoLocked">
                <el-select v-model="newUser.accountNoLocked" placeholder="请选择">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
            </el-select>
            </el-form-item>
            <el-form-item label="账号是否启用:" prop="accountEnabled">
                <el-select v-model="newUser.accountEnabled" placeholder="请选择">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
        <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submit()">
            确定
            </el-button>
        </div>
        </template>
    </el-dialog>
</template>

<script>
import { doGet, doPost, doPut, doDelete } from '../http/httpRequest';
import { messageTip, messageConfirm } from '../util/util';
export default {
    name:"userView",
    inject : ['reload'],
    data(){
        return {
            userList : [],
            pageSize : 0,
            total : 0,
            dialogVisible : false,
            newUser : {},
            // 标题
            Title : "",
            selectedIds : [],
            // 下拉选项
            options : [
                { label : "是", value : 1 },
                { label : "否", value : 0 }
            ],
            userRules : {                
                // 定义用户验证规则
                loginAct : [
                    { required: true, message: '登录账号不能为空', trigger: 'blur' },
                    { min: 3, max: 32, message: '登录账号长度范围为3-32个字符', trigger: 'blur' }
                ],
                loginPwd : [
                    { required: true, message: '登录密码不能为空', trigger: 'blur' },
                    { min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur' }
                ],
                name : [
                    { required: true, message: '姓名不能为空', trigger: 'blur' },
                    { pattern : /^[\u4e00-\u9fa5]{0,}$/, message: '姓名必须是中文汉字', trigger: 'blur'}
                ],
                phone : [
                    { required: true, message: '手机号码不能为空', trigger: 'blur' },
                    { pattern : /^1[3-9]\d{9}$/, message: '手机号码格式有误', trigger: 'blur'}
                ],
                email : [
                    { required: true, message: '邮箱不能为空', trigger: 'blur' },
                    { pattern : /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '邮箱格式有误', trigger: 'blur'}
                ],
                accountNoExpired : [
                    { required: true, message: '请选择账号是否未过期', trigger: 'blur' }
                ],
                credentialsNoExpired : [
                    { required: true, message: '请选择密码是否未过期', trigger: 'blur' }
                ],
                accountNoLocked : [
                    { required: true, message: '请选择账号是否未未锁定', trigger: 'blur' }
                ],
                accountEnabled : [
                    { required: true, message: '请选择账号是否可用', trigger: 'blur' }
                ]
            }
        }
    },
    mounted(){
        this.getData(1);
    },
    methods : {
        // 勾选或者取消勾选触发
        handleSelectionChange(selectionItems){
            this.selectedIds = [];
            // 将已经勾选的数据传给我们
            selectionItems.forEach(data => {
                this.selectedIds.push(data.id);
            });
        },
        batchDel(){
            if(!this.selectedIds.length){
                messageTip("请选择要删除的数据","warning");
                return;
            }
            messageConfirm("注意:删除后不可恢复","您确定要删除?").then(() => {
                let ids = this.selectedIds.join(",");
                doDelete("/api/user/batchDel",{ids : ids}).then(resp => {
                    if(resp.data.code === 200){
                        messageTip("批量删除成功","success");
                        this.reload();
                    }
                    else{
                        messageTip("批量删除失败:"+resp.data.msg,"error");
                    }
                });
            }).catch(() => {
              messageTip("已取消批量删除","warning");
            });  
        },
        submit(){
            this.$refs.userRefForm.validate((isValid) => {
                if(isValid){
                    let formData = new FormData();
                    for(let field in this.newUser){
                        if(this.newUser[field]){
                            formData.append(field,this.newUser[field]);
                        }
                    }
                    if(this.newUser.id){
                        doPut("/api/user/edit",formData).then(resp => {
                            if(resp.data.code === 200){
                                messageTip("修改成功","success");
                                this.dialogVisible = false;
                                this.reload();
                            }
                            else{
                                messageTip("修改失败","error");
                            }
                        });
                    }
                    else{
                        doPost("/api/user/add",formData).then(resp => {
                        if(resp.data.code === 200){
                            messageTip("提交成功","success");
                            this.dialogVisible = false;
                            this.reload();
                        }
                        else{
                            messageTip("提交失败","error");
                        }
                    });
                    }
                }
            });
        },
        // 自动传参
        toPage(current){
            // 把当前页作为current传递给获取数据方法,就可以实现分页查询了
            this.getData(current);
        },
        getData(current){
            //获取数据,查询用户列表数据
            doGet("api/users",{
                // 当前查询第几页
                current : current
            }).then(resp => {
                if(resp.data.code === 200){
                    this.userList = resp.data.data.list;
                    this.total = resp.data.data.total;
                    this.pageSize = resp.data.data.pageSize;
                }
                else{
                  messageTip("网络错误","error");
                }
            });
        },
        view(id){
            // $route是获取当前路由的属性信息,不要和router搞混了
            this.$router.push("/dashboard/user/detail/"+id);
        },
        edit(id){
            this.Title = "修改用户信息";
            // $router是调用路由对象的方法,如push跳转等
            this.dialogVisible = true;
            this.loadUser(id);
        },
        loadUser(id){
            doGet("/api/user/" + id,{}).then(resp => {
                if(resp.data.code === 200){
                    this.newUser = resp.data.data;
                    this.newUser.loginPwd = "";
                }
                else{
                  messageTip("网络错误","error");
                }
            });
        },
        del(id){
            messageConfirm("注意:删除后不可恢复","您确定要删除?").then(() => {
                // 点击确定按钮
                doDelete("/api/user/del/" + id,{}).then(resp => {
                    if(resp.data.code === 200){
                        messageTip('删除成功','success');
                        this.reload();
                    }
                    else{
                        messageTip('删除失败:'+resp.data.msg,'error');
                    }
                });
                }).catch(() => {
                // 点击取消按钮
                    messageTip("已取消删除",'warning');
            });
        },
        addUser(){
            this.newUser = {};
            this.dialogVisible = true;
            this.Title = "新增用户";
        }
    }
}
</script>

<style>
</style>